using BuildingBlocks.Application.Messaging;  
using BuildingBlocks.Domain;  
using Catalog.Api.Data;  
using Catalog.Api.Models;  
using MongoDB.Driver;  
  
namespace Catalog.Api.Features.CatalogItems.UpdateCatalogItem;  
  
internal sealed class UpdateCatalogItemCommandHandler(CatalogDbContext context)  
    : ICommandHandler<UpdateCatalogItemCommand>  
{  
    public async ValueTask<Result> Handle(UpdateCatalogItemCommand request, CancellationToken cancellationToken)  
    {  
        var filter = Builders<CatalogItem>.Filter.Eq(i => i.Id, request.Id);  
        var item = await context.CatalogItems.Find(filter).FirstOrDefaultAsync(cancellationToken);  
  
        if (item is null)  
        {  
            return Result.Failure(CatalogItemErrors.NotFound(request.Id));  
        }  
  
        var update = Builders<CatalogItem>.Update  
            .Set(i => i.Name, request.Name)  
            .Set(i => i.Description, request.Description)  
            .Set(i => i.Price, request.Price)  
            .Set(i => i.Stock, request.Stock)  
            .Set(i => i.PictureUrl, request.PictureUrl)  
            .Set(i => i.Category, request.Category);  
  
        await context.CatalogItems.UpdateOneAsync(filter, update, cancellationToken: cancellationToken);  
          
        return Result.Success();  
    }  
}
